/*
 * Leer y guardar archivo XML, NESESITA optimizar y separar, en una parte reutilisable y en la parte local del juego
 *
 * This is part of the game The Rooms
 * Copyright (C) 2010  Elvio Sarquis
 *
 * Get the GNU GPL v3 in http://www.gnu.org/licenses/
 */
package utils;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.BufferedOutputStream;
import java.io.IOException;

import rooms.Map;
import rooms.Character;
import rooms.PC;

public class XML {

    private static Character[] chars;
    private static Map map;

    private static final String CRLF = (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));

    public static boolean load(String file) {

        DocumentBuilderFactory dbFactory; //variables que se usan
        DocumentBuilder dBuilder;
        Document doc;
        NodeList nList;
        Node nNode;
        Element eElement;

        boolean loaded = true;
        int x = 0, y = 0;
        String[] mapstring;
        Character newone = null;

        chars = null; // inicializamos las variables temporales
        map = null;

        try {

            File fXmlFile = new File("Files/" + file + ".xml");            //No tengo idea que pasa aca...
            dbFactory = DocumentBuilderFactory.newInstance();
            dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            //Cargamos el mapa

            nList = doc.getElementsByTagName("map");

            nNode = nList.item(0);

            eElement = (Element) nNode;

            x = Integer.decode(getTagValue("x", eElement));
            y = Integer.decode(getTagValue("y", eElement));
            
            mapstring = new String[y];

            for (int i = 0; i < y; i++) {
                mapstring[i] = getTagValue("line" + i, eElement);
            }

            map = new Map(mapstring, x, y);

            //Cargamos los pnjs

            nList = doc.getElementsByTagName("enemy");
            chars = new Character[nList.getLength() + 1];

            for (int i = 0; i < nList.getLength(); i++) {
                nNode = nList.item(i);
                eElement = (Element) nNode;

                x = Integer.decode(getTagValue("x", eElement));
                y = Integer.decode(getTagValue("y", eElement));
                
                newone = new Character(x, y);
                newone.setId(i+1);
                newone.setHP(Integer.decode(getTagValue("hp", eElement)));
                newone.setMaxHP(Integer.decode(getTagValue("maxhp", eElement)));

                chars[i+1] = newone;
            }

            nList = doc.getElementsByTagName("pc");
            nNode = nList.item(0);
            eElement = (Element) nNode;

            newone = new PC();
            newone.setX(Integer.decode(getTagValue("x", eElement)));
            newone.setY(Integer.decode(getTagValue("y", eElement)));
            newone.setHP(Integer.decode(getTagValue("hp", eElement)));
            newone.setMaxHP(Integer.decode(getTagValue("maxhp", eElement)));

            chars[0] = newone;

        } catch (Exception e) {
            e.printStackTrace();
            loaded = false;
        }

        return loaded;
    }

    public static void loadKeys() {

      
    }

    public static void save(Map map, Character[] chars, String file) {

        String cont = "", line = "";

        cont = cont + "<save>" + CRLF;
        cont = cont + "<map>" + CRLF;

        cont = cont + "<x>" + map.getMapX() + "</x>" + CRLF;
        cont = cont + "<y>" + map.getMapY() + "</y>" + CRLF;

        for(int j = 0; j< map.getMapY(); j++){
        for(int i = 0; i< map.getMapX(); i++){

            line = line + map.getMapPoint(i, j);
        }
        cont = cont + "<line" + j + ">" + line + "</line" + j + ">" + CRLF;
        line="";
        }

        cont = cont + "</map>" + CRLF;
        cont = cont + "<enemies>" + CRLF;

        for(int i = 1; i <chars.length; i++){
            cont = cont + "<enemy>" + CRLF;

            cont = cont + "<x>" + chars[i].getX() + "</x>" + CRLF;
            cont = cont + "<y>" + chars[i].getY() + "</y>" + CRLF;
            cont = cont + "<hp>" + chars[i].getHP() + "</hp>" + CRLF;
            cont = cont + "<maxhp>" + chars[i].getMaxHP() + "</maxhp>" + CRLF;

            cont = cont + "</enemy>" + CRLF;
        }

        cont = cont + "<pc>" + CRLF;

        cont = cont + "<x>" + chars[0].getX() + "</x>" + CRLF;
        cont = cont + "<y>" + chars[0].getY() + "</y>" + CRLF;
        cont = cont + "<hp>" + chars[0].getHP() + "</hp>" + CRLF;
        cont = cont + "<maxhp>" + chars[0].getMaxHP() + "</maxhp>" + CRLF;

        cont = cont + "</pc>" + CRLF;

        cont = cont + "</enemies>" + CRLF;
        cont = cont + "</save>" + CRLF;

        try {
            OutputStream fout= new FileOutputStream("Files/" + file);
            OutputStream bout= new BufferedOutputStream(fout);
            OutputStreamWriter out = new OutputStreamWriter(bout, "8859_1");

            out.write(cont);

            out.flush();  // Don't forget to flush!
            out.close();
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }
}

    public static Map getMap(){
        return map;
    }
    
    public static Character[] getChars(){
        return chars;
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }
}
